//
//  ScencMainVC.m
//  SMTools
//
//  Created by fengsh on 2019/1/12.
//  Copyright © 2019年 fengsh. All rights reserved.
//

#import "ScencMainVC.h"
#import "DHxlsReaderOSX.h"
#import "ScencMembers.h"
#import <MagicalRecord/MagicalRecord.h>
#import "LuckyUtils.h"
#import "ExcelModel.h"
#import "ScencPrizeVC.h"
#import <Masonry/Masonry.h>
#import "ScenePrizedResultsVC.h"

extern int xls_debug;

@interface ScencMainVC ()<NSTableViewDelegate,NSTableViewDataSource,NSTabViewDelegate,NSMenuDelegate>
@property (weak) IBOutlet NSComboBox *cmb_department;
@property (weak) IBOutlet NSTableView *tableview;
@property (weak) IBOutlet NSTextField *tf_nmae;
@property (weak) IBOutlet NSTextField *tf_mobile;
@property (nonatomic, strong) NSMutableArray            *dataset;
@property (weak) IBOutlet NSTextField *lb_count;
@property (weak) IBOutlet NSTabView *tabs;
@property (nonatomic, strong) ScencPrizeVC              *settingPrizevc;
@property (nonatomic, strong) ScenePrizedResultsVC      *resultvc;
@end

@implementation ScencMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    self.dataset = [NSMutableArray array];
    
    NSMenu *tablemenu = [[NSMenu alloc]init];
    tablemenu.delegate = self;
    self.tableview.menu = tablemenu;
}

- (void)viewWillAppear
{
    [super viewWillAppear];
    [self.cmb_department removeAllItems];
    [self onSelected:nil];
}

- (void)reset
{
    [self.tf_nmae setStringValue:@""];
    [self.tf_mobile setStringValue:@""];
    [self.cmb_department setStringValue:@""];
}

- (IBAction)onBtnAdd:(id)sender {
    NSString *name = self.tf_nmae.stringValue;
    NSString *mobile = self.tf_mobile.stringValue;
    NSString *department = self.cmb_department.stringValue;
    
    name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    mobile = [mobile stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    department = [department stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (name.length == 0) {
        [LuckyUtils lucky_show:@"请输入姓名"];
        [self.tf_nmae becomeFirstResponder];
        return;
    }
    
    if (mobile.length == 0) {
        [LuckyUtils lucky_show:@"请输入手机号"];
        [self.tf_mobile becomeFirstResponder];
        return;
    }
    
    if (department.length == 0) {
        [LuckyUtils lucky_show:@"请输入部门"];
        [self.cmb_department becomeFirstResponder];
        return;
    }
    
    NSString *mid = [LuckyUtils uniqueid];
    
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        ScencMembers *add = [ScencMembers MR_createEntityInContext:localContext];
        add.mid = mid;
        add.name = name;
        add.department = department;
        add.mobile = mobile;
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        ScencMembers * newadd = [ScencMembers MR_findFirstByAttribute:@"mid" withValue:mid];
        [self.dataset insertObject:newadd atIndex:0];
        [self.lb_count setStringValue:[NSString stringWithFormat:@"参与人数:%ld",self.dataset.count]];
        [self.tableview reloadData];
        [self reset];
    }];
}

- (IBAction)onBtnDelete:(id)sender {
    NSInteger row = self.tableview.selectedRow;
//    NSLog(@"row = %ld",row);
    if (row != -1) {
        ScencMembers *del = self.dataset[row];
        
        [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
            NSPredicate *pr = [NSPredicate predicateWithFormat:@"mid = %@",del.mid];
            [ScencMembers MR_deleteAllMatchingPredicate:pr inContext:localContext];
        } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
            if (!error) {
                [self.dataset removeObjectAtIndex:row];
                [self.tableview reloadData];
            }
        }];
    }
}

- (IBAction)onSelected:(id)sender {
    NSString *p = @"";
    NSString *name = self.tf_nmae.stringValue;
    NSString *mobile = self.tf_mobile.stringValue;
    NSString *department = self.cmb_department.stringValue;
    
    name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    mobile = [mobile stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    department = [department stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (name.length > 0) {
        p = [p stringByAppendingString:[NSString stringWithFormat:@"name like '*%@*'",name]];
    }
    
    if (mobile.length > 0) {
        if (p.length > 0) {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"and mobile like '*%@*'",mobile]];
        } else {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"mobile like '*%@*'",mobile]];
        }
    }
    
    
    if (department.length > 0) {
        if (p.length > 0) {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"and department like '*%@*'",department]];
        } else {
            p = [p stringByAppendingString:[NSString stringWithFormat:@"department like '*%@*'",department]];
        }
    }
    
    NSArray *list = nil;
    if (p.length > 0) {
        NSPredicate *pre = nil;
        pre = [NSPredicate predicateWithFormat:p];
        list = [ScencMembers MR_findAllWithPredicate:pre];
    } else {
        list = [ScencMembers MR_findAll];
        [self.lb_count setStringValue:[NSString stringWithFormat:@"参与人数:%ld",list.count]];
    }
    
    if (list) {
        [self.dataset removeAllObjects];
        list = [[list reverseObjectEnumerator]allObjects];
        [self.dataset addObjectsFromArray:list];
        [self.tableview reloadData];
    }
}

- (IBAction)onBtnClean:(id)sender {
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        [ScencMembers MR_truncateAllInContext:localContext];
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        NSArray *list = [ScencMembers MR_findAll];
        [self.dataset removeAllObjects];
        [self.tableview reloadData];
        [self.lb_count setStringValue:[NSString stringWithFormat:@"参与人数:%ld",list.count]];
    }];
}

- (IBAction)onBtnExportIn:(id)sender {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    NSString *homes = NSHomeDirectory();
    [panel setDirectoryURL:[NSURL fileURLWithPath:homes]];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:YES];
    [panel setAllowedFileTypes:@[@"xls"]];
    [panel setAllowsOtherFileTypes:YES];
    if ([panel runModal] == NSOKButton) {
        NSString *path = [panel.URLs.firstObject path];
        //code
        NSLog(@"导入%@",path);
        dispatch_queue_t queue = dispatch_queue_create("com.fsh.readxls", 0);
        dispatch_async(queue, ^{
            [self readxlsInfo:path];
        });
    }
}

- (void)readxlsInfo:(NSString *)path
{
    DHxlsReader *reader = [DHxlsReader xlsReaderFromFile:path];
    assert(reader);
    
    /*
    NSString *text = @"";
    text = [text stringByAppendingFormat:@"AppName: %@\n", reader.appName];
    text = [text stringByAppendingFormat:@"Author: %@\n", reader.author];
    text = [text stringByAppendingFormat:@"Category: %@\n", reader.category];
    text = [text stringByAppendingFormat:@"Comment: %@\n", reader.comment];
    text = [text stringByAppendingFormat:@"Company: %@\n", reader.company];
    text = [text stringByAppendingFormat:@"Keywords: %@\n", reader.keywords];
    text = [text stringByAppendingFormat:@"LastAuthor: %@\n", reader.lastAuthor];
    text = [text stringByAppendingFormat:@"Manager: %@\n", reader.manager];
    text = [text stringByAppendingFormat:@"Subject: %@\n", reader.subject];
    text = [text stringByAppendingFormat:@"Title: %@\n", reader.title];

    text = [text stringByAppendingFormat:@"\n\nNumber of Sheets: %u\n", reader.numberOfSheets];
    */
    
    [reader startIterator:0];
    
    uint64 row = 1;
    BOOL ingoreHeader = YES;
    ExcelModel *item = nil;
    NSMutableArray *arr = [NSMutableArray array];
    
    if (!ingoreHeader) { //如果excel中第一行用来做数据表头即所谓的字段头时则不需要从1行开始读
        item = [[ExcelModel alloc]init];
        [arr addObject:item];
    }

    while (YES) {
        DHcell *cell = [reader nextCell];
        ///读完
        if (cell.type == cellBlank) break;
        
        if (cell.row != row) {
            row = cell.row;
            NSLog(@"新行==========");
            item = [[ExcelModel alloc]init];
            [arr addObject:item];
        }
        
        NSLog(@"第%hu行,第%hu列",cell.row,cell.col);
        NSString *cellvalue = [cell dump];
        
        switch (cell.col) {
            case 1: //姓名
            {
                item.name = cellvalue;
            }
                break;
            case 2: //手机号
            {
                item.mobile = cellvalue;
            }
                break;
            case 3: //部门
            {
                item.department = cellvalue;
            }
                break;
            default:
                break;
        }
    }
    
    [self.dataset removeAllObjects];
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext * _Nonnull localContext) {
        [ScencMembers MR_truncateAllInContext:localContext];
        for (ExcelModel *item in arr) {
            ScencMembers *add = [ScencMembers MR_createEntityInContext:localContext];
            add.mid = [LuckyUtils uniqueid];
            add.name = item.name;
            add.mobile = item.mobile;
            add.department = item.department;
        }
    } completion:^(BOOL contextDidSave, NSError * _Nullable error) {
        NSLog(@"保存 %hhd,Error=%@",contextDidSave,error);
        NSArray *list = [ScencMembers MR_findAll];
        if (list) {
            list = [[list reverseObjectEnumerator]allObjects];
            [self.dataset addObjectsFromArray:list];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.lb_count setStringValue:[NSString stringWithFormat:@"参与人数:%ld",list.count]];
                [self.tableview reloadData];
            });
        }
    }];
    
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.dataset.count;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 30;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSUserInterfaceItemIdentifier idf = tableColumn.identifier;
    NSTableCellView *cv = [tableView makeViewWithIdentifier:idf owner:nil];
    NSInteger colidx = [tableView columnWithIdentifier:idf];
    
    ScencMembers *member = self.dataset[row];
    
    switch (colidx) {
        case 0:
        {
            [cv.textField setStringValue:member.name?:@""];
        }
            break;
        case 1:
        {
            [cv.textField setStringValue:member.mobile?:@""];
        }
            break;
        case 2:
        {
            [cv.textField setStringValue:member.department?:@""];
        }
            break;
        case 3:
        {
            
        }
            break;
        case 4:
        {
            
        }
            break;
        case 5:
        {
            
        }
            break;
        case 6:
        {
            
        }
            break;
        default:
            break;
    }
    
    return cv;
}

//- (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
//{
//    if (row % 2 != 0) {
//        rowView.backgroundColor = [NSColor windowBackgroundColor];
//    }
//}

///标签切换
- (void)tabView:(NSTabView *)tabView willSelectTabViewItem:(nullable NSTabViewItem *)tabViewItem
{
    if ([tabViewItem.identifier isEqualToString:@"prize"]) {
        if (!self.settingPrizevc) {
            self.settingPrizevc = [[ScencPrizeVC alloc]init];
            [tabViewItem.view addSubview:self.settingPrizevc.view];
            
            [self.settingPrizevc.view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(@(0));
            }];
        }
    } else if ([tabViewItem.identifier isEqualToString:@"resultlist"]) {
        
        if (!self.resultvc) {
            self.resultvc = [[ScenePrizedResultsVC alloc]init];
            [tabViewItem.view addSubview:self.resultvc.view];
            
            [self.resultvc.view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(@(0));
            }];
        }
    }
}

- (void)menuNeedsUpdate:(NSMenu*)menu
{
//    [menu removeAllItems];
//    // 在这里动态添加 menu item
//    NSMenuItem *item = [[NSMenuItem alloc]initWithTitle:@"Delete" action:@selector(onDeleteClickedRow:) keyEquivalent:@""];
//    [menu addItem:item];
}

- (void)onDeleteClickedRow:(id)sender
{
    
}

@end
